package com.erp.app.report.genericInquiry;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import com.erp.framework.types.CustomBigInteger;

public class LoadReportClass extends ClassLoader
{
	public LoadReportClass() {}

	public ByteArrayOutputStream load(
			ActionMapping mapping,
			ActionForm formIn,
			HttpServletRequest request,
			HttpServletResponse response,
			ActionErrors errors,
			Servlet servlet,
			ArrayList rslt,
			String[] className,
			byte[][] content,
			CustomBigInteger[] isMainClass)
		throws Exception
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
//			boolean useDbClass = GenericInquiryConstants.USE_DB_CLASS; 
//			if(useDbClass){
				Class [] param = {
					ActionMapping.class,
					ActionForm.class,
					HttpServletRequest.class,
					HttpServletResponse.class,
					ActionErrors.class,
					Servlet.class,
					ArrayList.class
					};
				Object[] paramValue = {mapping,formIn,request,response,errors,servlet,rslt};
	
				Class reportClass = null;
				
				for(int i=0; i<className.length; i++){
					Class c = getClass(className[i],content[i]);
					if (isMainClass[i]!=null && isMainClass[i].intValue() == 1) {
						reportClass = c;
					}
					if (i == 0 && reportClass == null) {
						reportClass = c;
					}
				}
	
				Method reportMethod = reportClass.getMethod("getReport",param);
				Object obj = reportClass.newInstance();
	
				baos = (ByteArrayOutputStream) reportMethod.invoke(obj,paramValue);
//			} else {
//				String mainClassName = null;
//				for(int i=0; i<className.length; i++){
//					if (isMainClass[i]!=null && isMainClass[i].intValue() == 1) {
//						mainClassName = className[i];
//						break;
//					}
//					if (i == 0 && mainClassName == null) {
//						mainClassName = className[i];
//					}
//				}
//
//				SimpleReport sr = (SimpleReport) Class.forName(mainClassName).newInstance();
//				baos = sr.getReport(mapping,formIn,request,response,errors,servlet,rslt);
//			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return baos;
	}

	public Class loadClass(String arg0) throws ClassNotFoundException
	{
		return Class.forName(arg0);
	}

	public Class getClass(String name, byte[] b)
	{
		return super.defineClass(name, b, 0, b.length);
	}
}
